﻿using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using src;

namespace UnityExtensions
{
	public class ActionAsync
	{
		private QueueAsync<Action> mAction = new QueueAsync<Action>();

		public void AddAction(Action action)
		{
			if (action == null) return;//throw new ArgumentNullException("action");

			mAction.Enqueue(action);
		}


		public void Update()
		{

			if (mAction.Count == 0)
			{
				return;
			}
			mAction.DequeueAll(it=>it());
		}
	}

	public static class ActionAsyncer
	{

		public class AsyncInfo
		{
			public IAsyncResult Result;//
			public Action<AsyncInfo> Action;//
			public Action CompleteAction;//
			public object Data;
		}
		/// <summary>
		/// 在主线程中回调action
		/// </summary>
		/// <param name="action"></param>
		public static void CallInMainThread(Action action)
		{
			AppMain.ActionAsync.AddAction(action);
		}

		/// <summary>
		/// 异步调用action,完成后在主线程调用completeAction
		/// </summary>
		/// <param name="action">需要异步调用的函数</param>
		/// <param name="completeAction">异步调用完成后在主线程回调的函数</param>
		/// <param name="syncDebug">if true sync call action and completeAction,use to debug</param>
		public static AsyncInfo CallAsync([NotNull] Action<AsyncInfo> action, Action completeAction,bool syncDebug = false)
		{
			if (action == null) throw new ArgumentNullException("action");
			var callInfo = new AsyncInfo()
			{
				Action = action,
				CompleteAction = completeAction,

			};
			if (syncDebug)
			{
				action(callInfo);
				completeAction();
				return callInfo;
			}

			var result = action.BeginInvoke(callInfo,ar =>
			{
				var info = ar.AsyncState as AsyncInfo;
				info.Action.EndInvoke(ar);
				if (info.CompleteAction != null) CallInMainThread(info.CompleteAction);
			}, callInfo);
			callInfo.Result = result;
			return callInfo;
		}
	}
}
